<template>
  <div class="container">
    <div class="tableColumns">
      <!--组织架构-->
      <div class="left-tree">
          <span class="title-span">
              <span>{{ spanText }}</span>
          </span>
        <el-input class="unit-search" v-model="filterText" :suffix-icon="Search" placeholder="搜索单位名称"/>
        <el-tree ref="treeRefs"
                 :data="treeData"
                 :props="defaultProps"
                 default-expand-all
                 :filter-node-method="filterNode"
                 node-key="id"
                 :expand-on-click-node="false"
                 @node-click="handleNodeClick"
                 highlight-current>
        </el-tree>
      </div>
      <!--数据筛选 信息列表-->
      <div class="right-columns">
        <!-- 数据筛选-->
        <div class="table-select">
            <span class="title-span">
              <span>{{ spanText2 }}</span>
            </span>
          <el-form label-position="right">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="排班方案：" label-width="100px">
                  <el-input v-model="retrievedForm.schemeName" placeholder="请输入方案名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="班次类型：" label-width="100px">
                  <el-select v-model="retrievedForm.classType" placeholder="请选择">
                    <el-option v-for="item in classTypeArr" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="模式：" label-width="100px">
                  <el-select v-model="retrievedForm.schemeModel" placeholder="请选择">
                    <el-option v-for="item in optionsArr" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态：" label-width="100px">
                  <el-select v-model="retrievedForm.status" placeholder="请选择">
                    <el-option v-for="item in statusTypeArr" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!--<el-col :span="8">-->
              <!--  &lt;!&ndash;暂定&ndash;&gt;-->
              <!--  <el-form-item label="航站楼：" v-model="retrievedForm.terminal" label-width="100px"-->
              <!--                style="display: flex; align-items: center">-->
              <!--    <el-checkbox label="T3航站楼" size="large"/>-->
              <!--    <el-checkbox label="T5航站楼" size="large"/>-->
              <!--  </el-form-item>-->
              <!--</el-col>-->
            </el-row>
          </el-form>
          <div style="justify-content: flex-end;display: flex">
            <el-button @click="searchReset">清空</el-button>
            <el-button
              type="primary"
              @click="getList"
            >查询
            </el-button>
          </div>
        </div>
        <!--信息列表-->
        <div class="table-commons">
          <span class="title-span">
            <span>{{ spanText3 }}</span>
            <div style="display: flex;align-items: center">
              <!--<el-button type="primary">模板下载</el-button>
              <el-button type="primary">导入</el-button>-->
              <el-button type="primary" :disabled="nodeRowData.children.length!==0" @click="addRouter(1,{})"
                         style="margin-left: 10px">新增</el-button>
            </div>
          </span>
          <!--表格内容-->
          <table-common
            :loading="loading"
            :columns="exampleColumns"
            :pagination="pager"
            :table-data="tableData"
            @size-change="sizeChange"
            @current-change="currentChange"
            stripe
            :height="'450px'"
            @sort-change="sortChange"
          >
            <template #status="{ row }">
              <!-- 自定义操作栏示例  -->
              <div class="statusRow"
                   :style="{color:getColor(row.status),background:getBackColor(row.status),borderColor:getColor(row.status)}">
                {{ filterStatus(row.status) }}
              </div>
            </template>
            <template #action="{ row }">
              <!-- 自定义操作栏示例  -->
              <el-button v-if="row.status!=0||row.status!=2" class="link-btn" link type="primary"
                         @click="addRouter(2,row)">查看
              </el-button>
              <el-button v-if="row.status==0||row.status==1" class="link-btn" link type="primary"
                         @click="addRouter(3,row)">编辑
              </el-button>
              <el-button class="link-btn" link type="primary" @click="addRouter(4,row)">复制</el-button>
              <el-popconfirm v-if="row.status==0" title="是否作废?" confirmButtonText="确定" cancelButtonText="取消"
                             @confirm="() => deletepeoFn(data, row,3)">
                <template #reference>
                  <el-button class="link-btn" link type="danger">作废
                  </el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm v-if="row.status==1" title="是否终止?" confirmButtonText="确定" cancelButtonText="取消"
                             @confirm="() => deletepeoFn(data, row,4)">
                <template #reference>
                  <el-button class="link-btn" link type="danger">终止
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </table-common>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * @Name: 引入文件内容
 * @Author: cdfy2
 * @Date: 2023/16/13  16:25:31
 */
import { Search } from '@element-plus/icons-vue'
import { ElTree } from 'element-plus'
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { exampleColumns } from './config/columns'
import TableCommon from '@/components/TableCommon/index.vue'
import { useStore } from 'vuex'
import { greyPageList, updateStatus } from '@/api/quality/schedule'
import { getResource } from '@/api/resource'
import router from '@/router'

/**
 * @Name: 界面参数-start
 * @Author: cdfy2
 * @Date: 2023/16/13  16:19:57
 * @param:
 */
//分页表格查询参数
const retrievedForm = ref({
  schemeName: undefined,
  classType: undefined,
  schemeModel: undefined,
  status: undefined,
  terminal: undefined,
})
//模块名称
const spanText = ('组织架构')
const spanText2 = ('数据筛选')
const spanText3 = ('信息列表')
const filterText = ref('')
watch(filterText, (val) => {
  treeRefs.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.organizationName.includes(value)
}
// 请求用户的权限树
const { getters } = useStore()
// 拿到vuex里面用户的信息
const UserInfo = computed(() => getters['user/getOrganTree'])
//班次类型
const classTypeArr = ref<any>([])
//模式
const optionsArr = ref<any>([{
  value: 1,
  label: '人员'
}, {
  value: 2,
  label: '班组'
}])
//状态
const statusTypeArr = ref<any>([])

/**
 * @Name: 组织架构树-start
 * @Author: cdfy2
 * @Date: 2023/16/13  16:19:11
 * @param:
 */
//获取树
interface Tree {
  [key: string]: any
}

//格式化树
const organizes = computed(() => getters['user/getOrganTree'])
//树状态数据
const treeData = ref<Tree[]>([])
//参数名称更换
const defaultProps = {
  children: 'children',
  label: 'name',
  disabled: 'disabled',
}
//默认选中组织目录第一个
const treeRefs = ref<any>(null)
//当前点击节点事件
const nodeRowData = ref<any>({
  children: []
})
// 获取树形结构
const geTreeData = () => {
  treeData.value = ergodicTree(organizes.value)
  let names: any = localStorage.getItem('handleNodeRowNode')
  console.log(names)
  if (names !== null) {
    handleNodeClick(JSON.parse(names))
    getTopOne(JSON.parse(names), 1)
  } else {
    handleNodeClick(treeData.value[0])
    getTopOne(treeData.value[0], 2)
  }
}
const ergodicTree = (datas: any) => {
  datas.forEach((item: any) => {
    if (item.children.length > 0) {
      item.name = item.organizationName
      item.disabled = true
      ergodicTree(item.children)
    } else {
      item.id = item.organizationId
      item.name = item.organizationName
      item.catalogueId = item.organizationId
      item.children = []
    }
  })
  return datas
}
//默认选中组织目录第一个
const currentNodeData = ref()
const currentNodeKey = ref('')
const getTopOne = (data: any, types: number) => {
  if (data.children && data.children.length > 0) {
    getTopOne(data.children[0], types)
    if (types == 2) {
      if (data.children[0].children.length > 0) {
        handleNodeClick(data.children[0].children[0])
      } else {
        handleNodeClick(data.children[0])
      }
    }
  } else {
    nextTick(() => {
      currentNodeKey.value = data.id
      currentNodeData.value = data
      treeRefs.value.setCurrentKey(currentNodeKey.value)
    })
    return
  }
}

// 对树进行格式化
function convertData (data) {
  const result = []

  function traverse (node) {
    const newNode = {
      id: node.data.organId,
      label: node.data.name,
      value: node.data.organId,
      children: []
    }

    if (node.children.length > 0) {
      node.children.forEach((child) => {
        newNode.children.push(traverse(child))
      })
    }

    return newNode
  }

  data.forEach((node) => {
    result.push(traverse(node))
  })

  const rootNode = {
    id: 'root',
    label: '全部',
    value: 'root',
    children: result
  }

  return [rootNode]
}

// 左侧组织架构节点事件
const handleNodeClick = (data: any) => {
  nodeRowData.value = data
  localStorage.setItem('handleNodeRowNode', JSON.stringify(data))
  getList()
}

/**
 * @Name: 获取字典数据
 * @Author: cdfy2
 * @Date: 2023/16/13  16:25:55
 * @param:  enclosure_type
 */

const loadDict = async () => {
  Promise.all([
    getResource('tcdm_class_type'),
    getResource('scheme_status'),
  ]).then(([res1, res2]) => {
    if (res1?.code === '1') {
      classTypeArr.value = res1.data.properties.meta
    }

    if (res2?.code === '1') {
      statusTypeArr.value = res2.data.properties.meta
    }

  })
}

/**
 * @Name: 表格分页
 * @Author: cdfy2
 * @Date: 2023/16/13  16:26:05
 * @param:
 */
// 获取列表信息
const tableData = ref([])
// 表格分页
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0,
})

interface OrderItem {
  column?: string
  method?: string
}
const sortChange = (data: any) => {
  console.log(data)
  const method = data.order === 'ascending' ? 'asc' : 'desc'
  order.value[0].column =data.prop
  order.value[0].method = method
  getList()
}


// 切换每页条数
const sizeChange = (size: number) => {
  pager.currentPage = 1
  pager.pageSize = size
  getList()
}
//切换当前页
const currentChange = (value: any) => {
  pager.currentPage = value
  pager.pageSize = 10
  getList()
}
//获取分页参数方法
const getList = async () => {
  //分页参数
  const params = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      deptId: nodeRowData.value.id,
      classType: retrievedForm.value.classType,
      schemeModel: retrievedForm.value.schemeModel,
      schemeName: retrievedForm.value.schemeName,
      status: retrievedForm.value.status,
      orderBy:order.value[0].column,
      collation:order.value[0].method,
    },
  }
  // 返回分页查询的结果
  const res = await greyPageList(params)
  if (res?.code == '1') {
    // 信息列表数据
    tableData.value = res.data.list
    pager.total = res.data.total
    pager.pageCount = Math.ceil(pager.total / pager.pageSize) === 0 ? 1 : Math.ceil(pager.total / pager.pageSize)
  }
}
//清空重置
const order = ref([{
  'column': 'status',
  'method': 'desc'
}] as OrderItem[])
const searchReset = (data: any) => {
  retrievedForm.value = {
    schemeName: undefined, //排班方案
    classType: undefined,//班次类型
    schemeModel: undefined,//模式
    status: undefined,//状态
    terminal: undefined,//航站楼
  }
  order.value = [{
    'column': 'status',
    'method': 'desc'
  }]
  pager.currentPage = 1
  pager.pageSize = 10
  tableData.value = []
  getList()
}
//作废  终止
const deletepeoFn = (data: any, row: any, status: any) => {
  let parem = {
    id: row.id,
    status: status
  }
  updateStatus(parem).then(resp => {
    if (resp.code === '1') {
      getList()
    }
  })
}
const filterStatus = (status: any) => {
  let dictName = ''
  statusTypeArr.value.filter((item: any) => {
    if (status == item.value) {
      dictName = item.label
    }
  })
  return dictName
}
const getColor = (status: any) => {
  let color=''
  switch (status) {
    case 0:
      color='#3684E9'
      break
    case 1:
      color='#F9B87D'
      break
    case 2:
      color='#74C48B'
      break
    case 3:
    case 4:
      color='#9B9B9B'
      color='#9B9B9B'
      break
  }
  return color
}
const getBackColor = (status: any) => {
  let color=''
  switch (status) {
    case 0:
      color='#E3F4FE'
      break
    case 1:
      color='#FFF4E5'
      break
    case 2:
      color='#E7FDE8'
      break
    case 3:
    case 4:
      color='#f5f5f5'
      color='#f5f5f5'
      break
  }
  return color
}
//跳转接口
const addRouter = (data: any, row: any) => {
  if (data === 1) {
    router.push({
      path: '/quality/programme/add',
      query: {
        nodeRowData: nodeRowData.value.id,
      }
    })
  } else {
    router.push({
      path: '/quality/programme/details',
      query: {
        type: data,
        nodeRowData: nodeRowData.value.id,
        tableId: row.id
      }
    })
  }

}
/**
 * @Name: 页面挂在后执行
 * @Author: cdfy2
 * @Date: 2023/16/13  16:27:29
 */
onMounted(() => {
  let forward: any = router.options.history.state.forward
  if (forward == null) {
    localStorage.removeItem('handleNodeRowNode')
  }
  geTreeData()
  loadDict()
})
</script>

<style scoped lang="less">
@import "../style/publicStyle.less";

.container {
  .tableColumns {

    .table-select {
      height: 165px;
    }
  }
}

.statusRow {
  width: 80px;
  padding: 2px 5px;
  margin: 0 auto;
  border: 1px solid #ebeef5;
  background: #0e595e;
  color: #ebeef5;
  border-radius: 5px;
}
</style>
